<template>
  <div>
    <!-- 头部 -->
    <myDivider :name="scene == 'add' ? '新增发票' : '修改发票'"></myDivider>
    <el-page-header @back="$router.push('/invoice/invoiceList')">
    </el-page-header>

    <!-- form表单 -->
    <el-form style="margin-left: 20px" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px"
      label-position="left">
      <el-row style="margin: 20px 0;">
        <el-col :span="12">
          <div style="display: flex;align-items: center;">
            <i class="el-icon-user-solid" style="transform: scale(1.5);margin-right: 15px;"></i>
            <div>购买方信息</div>
          </div>
        </el-col>
        <el-col :span="12">
          <div style="display: flex;align-items: center;">
            <i class="el-icon-user-solid" style="transform: scale(1.5);margin-right: 15px;"></i>
            <div>销售方信息</div>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="名称：" prop="buyerInformation.name">
            <el-input size="medium" style="width: 350px" maxlength="20" v-model="ruleForm.buyerInformation.name"
              placeholder="请输入名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称：" prop="sellerInformation.name">
            <el-input size="medium" style="width: 350px" maxlength="20" v-model="ruleForm.sellerInformation.name"
              placeholder="请输入名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="纳税人识别号：">
            <el-input size="medium" style="width: 350px" maxlength="13" v-model="ruleForm.buyerInformation.taxpayerId"
              placeholder="请输入纳税人识别号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纳税人识别号：">
            <el-input size="medium" style="width: 350px" maxlength="13" v-model="ruleForm.sellerInformation.taxpayerId"
              placeholder="请输入纳税人识别号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="地址、电话：">
            <el-input size="medium" style="width: 350px" maxlength="50" v-model="ruleForm.buyerInformation.addressTel"
              placeholder="请输入地址、电话"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地址、电话：">
            <el-input size="medium" style="width: 350px" maxlength="50" v-model="ruleForm.sellerInformation.addressTel"
              placeholder="请输入地址、电话"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="开户行及账号：">
            <el-input size="medium" style="width: 350px" maxlength="50"
              v-model="ruleForm.buyerInformation.bankInformation" placeholder="请输入开户行及账号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户行及账号：">
            <el-input size="medium" style="width: 350px" maxlength="50"
              v-model="ruleForm.sellerInformation.bankInformation" placeholder="请输入开户行及账号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 其他信息 -->
      <!-- 其他信息 -->
      <!-- 其他信息 -->
      <el-row style="margin: 20px 0;">
        <el-col :span="24">
          <div style="display: flex;align-items: center;">
            <i class="el-icon-s-grid" style="transform: scale(1.5);margin-right: 15px;"></i>
            <div>其他信息</div>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="发票代码：">
            <el-input size="medium" style="width: 255px;"
              oninput="value=value.replace(/[^\d]/g,'');if(value.length>15){value=value.slice(0,15)}" maxlength="15"
              v-model="ruleForm.invoiceCode" placeholder="请输入发票代码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票号码：" prop="number">
            <el-input size="medium" style="width: 255px;" type="number"
              oninput="if(value.length>15){value=value.slice(0,15)}" v-model="ruleForm.number"
              placeholder="请输入发票代码"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="开票日期：" prop="invoicingDate">
            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期"
              v-model="ruleForm.invoicingDate" style="width: 255px;"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格型号：">
            <el-input size="medium" style="width: 255px;" maxlength="15" v-model="ruleForm.model"
              placeholder="请输入规格型号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="货物或应税劳务、服务名称：" prop="serviceName" label-width="220px">
        <el-input size="medium" style="width: 580px;" maxlength="50" v-model="ruleForm.serviceName"
          placeholder="请输入"></el-input>
      </el-form-item>

      <el-row>
        <el-col :span="4">
          <el-form-item label="单位：" label-width="55px">
            <el-input size="medium" style="width: 120px;" maxlength="5" v-model="ruleForm.unit"
              placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="数量：" label-width="55px">
            <el-input size="medium" style="width: 120px;"
              oninput="value=value.replace(/[^\d]/g,'');if(value.length>10){value=value.slice(0,10)}"
              v-model="ruleForm.count" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="单价：" label-width="55px">
            <el-input size="medium" style="width: 120px;"
              oninput="value=value.match(/\d+\.?\d{0,2}/);if(value.length>10){value=value.slice(0,10)}"
              v-model="ruleForm.unitPrice" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="金额：" label-width="55px">
            <el-input size="medium" style="width: 120px;"
              oninput="value=value.match(/\d+\.?\d{0,2}/);if(value.length>10){value=value.slice(0,10)}"
              v-model="ruleForm.totalPrice" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="税率：" label-width="55px">
            <el-input size="medium" style="width: 120px;" oninput="if(value.length>2){value=value.slice(0,2)}"
              v-model="ruleForm.taxRate" placeholder="请输入"></el-input>
            <span>%</span>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="税额：" label-width="55px">
            <el-input size="medium" style="width: 120px;"
              oninput="value=value.match(/\d+\.?\d{0,2}/);if(value.length>10){value=value.slice(0,10)}"
              v-model="ruleForm.taxAmount" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="金额合计：" label-width="100px">
            <el-input size="medium" style="width: 155px;"
              oninput="value=value.match(/\d+\.?\d{0,2}/);if(value.length>20){value=value.slice(0,20)}"
              v-model="ruleForm.totalPriceSummation" placeholder="请输入金额总数"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="税额合计：" label-width="100px">
            <el-input size="medium" style="width: 155px;"
              oninput="value=value.match(/\d+\.?\d{0,2}/);if(value.length>20){value=value.slice(0,20)}"
              v-model="ruleForm.taxAmountSummation" placeholder="请输入税额总数"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="价税合计：￥" label-width="100px">
            <el-input size="medium" style="width: 155px;"
              oninput="value=value.match(/\d+\.?\d{0,2}/);if(value.length>20){value=value.slice(0,20)}"
              v-model="ruleForm.priceTaxSummation" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="收款人：" label-width="100px">
            <el-input size="medium" style="width: 155px;" maxlength="10" v-model="ruleForm.payee"
              placeholder="请输入收款人"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="复核：" label-width="100px">
            <el-input size="medium" style="width: 155px;" maxlength="10" v-model="ruleForm.invoiceCheck"
              placeholder="请输入复核"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开票人：" label-width="100px">
            <el-input size="medium" style="width: 155px;" maxlength="10" v-model="ruleForm.drawer"
              placeholder="请输入开票人"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="关联小区：" label-width="100px" prop="residentialId">
        <el-select style="width: 520px;" ref="residentialSelect" v-model="ruleForm.residentialId" placeholder="请选择小区"
          @change="residentialChange">
          <el-option v-for="item, i in residentialData" :key="i" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注：" label-width="100px">
        <el-input size="medium" type="textarea" :rows="5" style="width: 800px;" placeholder="请输入内容"
          v-model="ruleForm.notes" maxlength="200" show-word-limit></el-input>
      </el-form-item>


      <!-- 附件 -->
      <!-- 附件 -->
      <!-- 附件 -->
      <el-row style="margin: 20px 0;">
        <el-col :span="24">
          <div style="display: flex;align-items: center;">
            <i class="el-icon-upload" style="transform: scale(1.5);margin-right: 15px;"></i>
            <div>附件</div>
          </div>
        </el-col>
      </el-row>

      <el-form-item label="图片：" label-width="100px">
        <MyUploadImgNotDetele v-if="MyUploadImgNotDetele" ref="MyUploadImgNotDetele" :canUploadNum="1"
          @deleteImgList="deleteImgList" @getImgList="getImgList" :id="ImgId" :EchoImgList="EchoImgList"
          uploadUrl="/business/invoice/uploadImg">
        </MyUploadImgNotDetele>
      </el-form-item>
      <el-form-item label="电子发票：" label-width="100px">
        <MyUploadFileNotDetele v-if="MyUploadFileNotDetele" :id="FileId" ref="MyUploadFileNotDetele" :canUploadNum="1"
          @deleteFileList="deleteFileList" @getFileList="getFileList" :EchoFileList="EchoFileList"
          uploadUrl="/business/invoice/uploadAnnex">
        </MyUploadFileNotDetele>
      </el-form-item>
      <el-form-item label="经办人：" label-width="100px">
        <el-input style="width: 200px;" v-model="ruleForm.createUserName" disabled placeholder=""></el-input>
      </el-form-item>
      <el-form-item class="btn">
        <el-button style="width: 100px;" type="primary" @click="onSubmit">{{ scene == 'add' ? '新增' : '修改' }}</el-button>
        <el-button style="width: 100px;" type="info" @click="$router.push('/invoice/invoiceList')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'
import MyUploadFileNotDetele from '@/components/upload/MyUploadFileNotDetele'
import MyUploadImgNotDetele from '@/components/upload/MyUploadImgNotDetele'
export default {
  components: {
    MyUploadImgNotDetele,
    MyUploadFileNotDetele
  },

  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入发票号码'));
      } else {
        if (value.indexOf('.') > -1) {
          callback(new Error('请正确输入发票号码'));
        } else {
          callback();

        }
      }
    };
    return {
      residentialData: [],
      userData: {},
      //图片相关
      MyUploadImgNotDetele: false,
      ImgId: 0,
      EchoImgList: [],//要回显的图片
      deleteImgs: [], //要删除的图片列表
      //附件相关
      MyUploadFileNotDetele: false,
      FileId: 0,
      EchoFileList: [],//要回显的附件
      deleteFiles: [], //要删除的附件列表
      scene: '',
      ruleForm: {
        buyerInformation: {},
        sellerInformation: {}
      },
      rules: {
        "buyerInformation.name": [
          { required: true, message: '请输入购买方名称', trigger: 'blur' },
        ],
        "sellerInformation.name": [
          { required: true, message: '请输入销售方名称', trigger: 'blur' },
        ],
        residentialId: [
          { required: true, message: '请选择关联小区', trigger: 'change' },
        ],
        number: [
          { required: true, message: '请输入发票号码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        invoicingDate: [
          { required: true, message: '请选择开票日期', trigger: 'change' },
        ],

        serviceName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
      },
      ImgList: [`${defaultUrl}/image/tempImage/contract/31d5f73f6a-.jpg`],
      FileList: [],
    }
  },
  async activated() {
    this.scene = this.$route.query.scene //当前页面场景，新增还是修改
    this.userData = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.getResidentialData() //获取小区列表
    // 清空图片和附件相关数据
    this.MyUploadImgNotDetele = false
    this.MyUploadFileNotDetele = false
    this.EchoImgList = []
    this.deleteImgs = []
    this.EchoFileList = []
    this.deleteFiles = []

    setTimeout(async () => {
      switch (this.scene) {
        case 'add':
          { //清空数据
            this.ImgId = 0
            this.FileId = 0
            this.$set(this.ruleForm, 'annexUrl', '')
            this.$set(this.ruleForm.buyerInformation, 'addressTel', '')
            this.$set(this.ruleForm.buyerInformation, 'bankInformation', '')
            this.$set(this.ruleForm.buyerInformation, 'name', '')
            this.$set(this.ruleForm.buyerInformation, 'taxpayerId', '')
            this.$set(this.ruleForm.sellerInformation, 'addressTel', '')
            this.$set(this.ruleForm.sellerInformation, 'bankInformation', '')
            this.$set(this.ruleForm.sellerInformation, 'name', '')
            this.$set(this.ruleForm.sellerInformation, 'taxpayerId', '')
            this.$set(this.ruleForm, 'count', '')
            this.$set(this.ruleForm, 'drawer', '')
            this.$set(this.ruleForm, 'imageUrl', '')
            this.$set(this.ruleForm, 'invoiceCheck', '')
            this.$set(this.ruleForm, 'invoiceCode', '')
            this.$set(this.ruleForm, 'invoicingDate', '')
            this.$set(this.ruleForm, 'model', '')
            this.$set(this.ruleForm, 'notes', '')
            this.$set(this.ruleForm, 'number', '')
            this.$set(this.ruleForm, 'payee', '')
            this.$set(this.ruleForm, 'priceTaxSummation', '')
            this.$set(this.ruleForm, 'serviceName', '')
            this.$set(this.ruleForm, 'taxAmount', '')
            this.$set(this.ruleForm, 'taxAmountSummation', '')
            this.$set(this.ruleForm, 'taxRate', '')
            this.$set(this.ruleForm, 'totalPrice', '')
            this.$set(this.ruleForm, 'totalPriceSummation', '')
            this.$set(this.ruleForm, 'unit', '')
            this.$set(this.ruleForm, 'unitPrice', '')
            this.$set(this.ruleForm, 'residentialId', '')
            
          }
          this.ruleForm.createUserName = this.userData.name
          this.MyUploadImgNotDetele = true
          this.MyUploadFileNotDetele = true
          break
        case 'update':
          let res = await this.$api.message.myInvoiceDetail(this.$route.query.id)
          this.ImgId = res.data.id
          this.FileId = res.data.id
          console.log(res, 'detail');
          if (res.code == 200) {
            this.ruleForm = res.data
            if (this.ruleForm.count == 0) this.ruleForm.count = null
            if (this.ruleForm.unitPrice == 0) this.ruleForm.unitPrice = null
            if (this.ruleForm.totalPrice == 0) this.ruleForm.totalPrice = null
            if (this.ruleForm.taxRate == 0) this.ruleForm.taxRate = null
            if (this.ruleForm.taxAmount == 0) this.ruleForm.taxAmount = null
            if (this.ruleForm.totalPriceSummation == 0) this.ruleForm.totalPriceSummation = null
            if (this.ruleForm.taxAmountSummation == 0) this.ruleForm.taxAmountSummation = null
            if (this.ruleForm.priceTaxSummation == 0) this.ruleForm.priceTaxSummation = null
            // 回显图片/附件
            if (res.data.imageUrl) this.EchoImgList.push(res.data.imageUrl)
            if (res.data.annexUrl) this.EchoFileList.push(res.data.annexUrl)

            this.MyUploadImgNotDetele = true
            this.MyUploadFileNotDetele = true

          } else {
            this.$message.error(res.message)
          }


          break
      }
      this.$nextTick(() => { //清除验证
        this.$refs.ruleForm.clearValidate()
      })
    }, 1)


  },
  methods: {
    async getResidentialData() {
      let logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
      let res = await this.$api.contract.myGetCommunityList({
        "unitType": logOnUser.unitType, //匹配当前登录人单位  机关agency 机构company 系统system
        "unitId": logOnUser.unitId //系统传0
      })
      if (res.code == 200) {
        this.residentialData = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    residentialChange() { //所选小区切换事件
      this.$nextTick(() => {
        this.$set(this.ruleForm, 'residentialName', this.$refs.residentialSelect.selectedLabel)
      })

    },
    onSubmit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$confirm('请检查无误后提交', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            //删除图片 和附件
            if (this.deleteImgs.length > 0) {
              this.deleteImgs.forEach(async el => {
                let params = {
                  "imageUrl": el
                }
                let res = await this.$api.ImgFile.delete(defaultUrl+'/business/invoice/deleteImg', params)
              })
            }
            if (this.deleteFiles.length > 0) {
              this.deleteFiles.forEach(async el => {
                let params = {
                  "filePath": el
                }
                let res = await this.$api.ImgFile.delete(defaultUrl+'/business/invoice/deleteAnnex', params)
              
              })
            }


            if (this.scene == 'add') {
              let user = JSON.parse(sessionStorage.getItem('logOnUser'))
              this.ruleForm.unitId = user.unitId
              this.ruleForm.unitType = user.unitType
              let {
                buyerInformation,
                sellerInformation,
                annexUrl,
                count,
                drawer,
                imageUrl,
                invoiceCheck,
                invoiceCode,
                invoicingDate,
                model,
                notes,
                number,
                payee,
                priceTaxSummation,
                serviceName,
                taxAmount,
                taxAmountSummation,
                taxRate,
                totalPrice,
                totalPriceSummation,
                unit,
                unitPrice,
                unitId,
                unitType,
                residentialId,
                residentialName
               } = this.ruleForm
              let params = {
                buyerInformation,
                sellerInformation,
                annexUrl,
                count,
                drawer,
                imageUrl,
                invoiceCheck,
                invoiceCode,
                invoicingDate,
                model,
                notes,
                number,
                payee,
                priceTaxSummation,
                serviceName,
                taxAmount,
                taxAmountSummation,
                taxRate,
                totalPrice,
                totalPriceSummation,
                unit,
                unitPrice,
                unitId,
                unitType,
                residentialId,
                residentialName
              }
              let res = await this.$api.message.myInvoiceAdd(params)
              if (res.code == 200) {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                });
                this.$router.push('/invoice/invoiceList')
              } else {
                this.$message.error(res.message)
              }
            }
            if (this.scene == 'update') {
              let {
                buyerInformation,
                sellerInformation,
                annexUrl,
                count,
                drawer,
                imageUrl,
                invoiceCheck,
                invoiceCode,
                invoicingDate,
                model,
                notes,
                number,
                payee,
                priceTaxSummation,
                serviceName,
                taxAmount,
                taxAmountSummation,
                taxRate,
                totalPrice,
                totalPriceSummation,
                unit,
                unitPrice,
                id, 
                residentialId,
                residentialName
              } = this.ruleForm
              let params = {
                buyerInformation,
                sellerInformation,
                annexUrl,
                count,
                drawer,
                imageUrl,
                invoiceCheck,
                invoiceCode,
                invoicingDate,
                model,
                notes,
                number,
                payee,
                priceTaxSummation,
                serviceName,
                taxAmount,
                taxAmountSummation,
                taxRate,
                totalPrice,
                totalPriceSummation,
                unit,
                unitPrice,
                id,
                residentialId,
                residentialName
              }
              let res = await this.$api.message.myupdateInvoice(params)
              if (res.code == 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.$router.push('/invoice/invoiceList')
              } else {
                this.$message.error(res.message)
              }
            }
          }).catch(() => {

          });

        } else {
          console.log('error submit!!');
        }
      });
    },
    getImgList(val) {//最终图片列表
      if (val.length == 0) {
        this.ruleForm.imageUrl = ''
        return
      }
      this.ruleForm.imageUrl = val[0]
    },
    deleteImgList(val) {  //要删除的图片列表
      this.deleteImgs.push(val)
    },
    getFileList(val) {//最终附件列表
      if (val.length == 0) {
        this.ruleForm.annexUrl = ''
        return
      }
      this.ruleForm.annexUrl = val[0]
    },
    deleteFileList(val) {  //要删除的附件列表

      this.deleteFiles.push(val)
    },
  },
}
</script>

<style lang="less" scoped>
.btn {
  position: fixed;
  bottom: 10px;
  right: 70px;
}
</style>